package com.yysoft.core.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.yysoft.core.utils.UserSessionUtils;
import com.yysoft.core.utils.annotation.AuthUser;
import com.yysoft.core.web.model.AjaxResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import java.io.PrintWriter;

/**
 * @author pany
 * 所需登录验证的方法加入注解@Auth即可
 * 
 */
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {

	private static Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);
	
	/** 
     * Controller方法调用之前调用
     * SpringMVC的这种Interceptor链式结构也是可以进行中断的，这种中断方式是令preHandle的返 
     * 回值为false，当preHandle的返回值为false的时候整个请求就结束了。 
     */
    @Override  
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	try {
    		if(handler instanceof HandlerMethod){
    			HandlerMethod method = (HandlerMethod)handler;
				AuthUser controllerLoginFlag = method.getBean().getClass().getAnnotation(AuthUser.class);
				AuthUser methodLoginFlag = method.getMethodAnnotation(AuthUser.class);
    			String controllerName = method.getBean().getClass().getName();
    			String methodName = method.getMethod().getName();
    			if((controllerLoginFlag!=null||methodLoginFlag!=null) && UserSessionUtils.getUserSession(request)==null){
    				logger.info("用户未登录拦截："+request.getRequestURI());
    				logger.info(controllerName+"."+methodName+"()");

					AjaxResponse ajaxResponse = new AjaxResponse(50018,"请先登录");
					response.setContentType("text/html; charset=UTF-8");
					PrintWriter pw = response.getWriter();
					pw.write(JSON.toJSONString(ajaxResponse));
					pw.flush();
					pw.close();

    				return false;
    			}
    		}
		} catch (Exception e) {
			logger.error("", e);
		}
        return true;
    }

}